package com.mvc.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;

import com.cdkey.EventInMsg;
import com.cdkey.InMsg;
import com.cdkey.InMsgParser;
import com.cdkey.InTextMsg;
import com.cdkey.MDUtil;
import com.cdkey.OutTextMsg;
import com.cdkey.WXConfig;
import com.common.core.BaseController;
import com.mvc.model.CDKey;
import com.mvc.request.ReqCDKeyQPage;
import com.mvc.request.ReturnData;
import com.mvc.service.CDKeyService;
import com.mvc.service.impl.CDkeyServiceImpl;

/***
 * 微信
 * 
 * @author Administrator
 * 
 */
public class WXGameController extends BaseController {

	public static final String TOKEN = "GameCodeKey9999";
	CDKeyService cdKeyService = new CDkeyServiceImpl();

	// 微信+ 获取条件搜索
	public void query() throws IOException {
		HttpServletRequest request = getRequest();

		String method = request.getMethod();
		if ("GET".equals(method)) {
			proving();
			return;
		} 
		
		if ("POST".equals(method)) {
			String xml = getRequestStr().toString();

			InMsg inMsg = InMsgParser.parse(xml);
			if (inMsg == null) 
			{
				renderText("success", "text/xml");
				return;
			}
			WXConfig config = WXConfig.getInstace();
			
			//文本信息
			if (inMsg instanceof InTextMsg)
			{
				InTextMsg inTextMsg = (InTextMsg) inMsg;
				sendGameCode(inTextMsg,config);
				return;
			}
			
			//事件
			if(inMsg instanceof EventInMsg)
			{
				OutTextMsg outTextMsg = new OutTextMsg(inMsg);
				outTextMsg.setContent(config.getConfig().getWelcome());
				renderText(outTextMsg.toXml(), "text/xml");
				return;
			}
		}
	}

	// 发激活码
	private void sendGameCode(InTextMsg inTextMsg,WXConfig config)
	{
		ReqCDKeyQPage req = new ReqCDKeyQPage();
		req.setSearch(inTextMsg.getContent().trim());

		ReturnData<CDKey> data = cdKeyService.queryObject(req);

		OutTextMsg outTextMsg = new OutTextMsg(inTextMsg);

		if (data.getCode() == 200) {
			String codeKey = data.getData().getStr(
					CDKey.TableField.CODEKEY.value);
			outTextMsg.setContent(codeKey);

		} else {
			outTextMsg.setContent(config.getConfig().getError());
		}

		renderText(outTextMsg.toXml(), "text/xml");
	}
	
	
	//step1微信服务验证
	private void proving() throws IOException {
		HttpServletRequest request = getRequest();
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = getResponse().getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (MDUtil.checkSignature(TOKEN,signature, timestamp, nonce)) {
			out.print(echostr);
			System.out.println("微信服务验证成功！");
		}
		out.close();
		out = null;
	}

	//车找人，四月一号下午17点下班后南京回泗洪，武定门地铁站出发，途径新庄地铁站，可带三人，电话15951099350
	
}
